require 'digest'
class User < ActiveRecord::Base
  attr_accessor :password
  
  validates :username, :uniqueness => true
  validates :password, :confirmation => true,
                        :length => { :within => 4..20 },
                        :presence => true,
                        :if => :password_required?

  has_one :profile
  has_many :events
  has_many :articles
  has_many :videos
  has_many :article_approvals
  has_many :news
  has_many :images
  has_many :video_comments, :dependent => :destroy
  
  has_and_belongs_to_many :roles
 
  before_save :encrypt_new_password
  
  def self.authenticate(username, password)
    user = find_by_username(username)
    return user if user && user.authenticated?(password)
  end
  
  def authenticated?(password)
    self.hashed_password == encrypt(password)
  end
  
  def isRole?(role)
    begin
      self.roles.find(role)
      return true
    rescue ActiveRecord::RecordNotFound      
      return false
    end
  end
  
  protected
    def encrypt_new_password
      return if password.blank?
      self.hashed_password = encrypt(password)
    end
    
    def password_required?
      hashed_password.blank? || password.present?
    end
    
    def encrypt(string)
      Digest::SHA1.hexdigest(string)
    end
end
